package co.yixiang.modules.auction.rest;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException;
import co.yixiang.common.aop.NoRepeatSubmit;
import co.yixiang.common.aop1.AppNoRepeatSubmit;
import co.yixiang.common.bean.LocalUser;
import co.yixiang.common.interceptor.AuthCheck;
import co.yixiang.constant.ShopConstants;
import co.yixiang.enums.AuctionOrderEnum;
import co.yixiang.enums.BillDetailEnum;
import co.yixiang.enums.BillEnum;
import co.yixiang.enums.ShopCommonEnum;
import co.yixiang.modules.auction.domain.YxAuctionOrder;
import co.yixiang.modules.auction.domain.YxAuctionRecord;
import co.yixiang.modules.auction.param.YxAuctionOrderParam;
import co.yixiang.modules.auction.service.YxAuctionOrderService;
import co.yixiang.modules.auction.service.YxAuctionRecordService;
import co.yixiang.modules.auction.service.dto.YxAuctionOrderConfirm;
import co.yixiang.modules.auction.service.dto.YxAuctionOrderList;
import co.yixiang.modules.auction.service.dto.YxAuctionRecordDto;
import co.yixiang.modules.auction.service.mapper.YxAuctionOrderMapper;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.domain.YxUserBill;
import co.yixiang.modules.user.service.YxUserBillService;
import co.yixiang.modules.user.service.mapper.UserMapper;
import co.yixiang.utils.PushtoSingle;
import co.yixiang.utils.RandonOrderNoUtil;
import co.yixiang.utils.RedisUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@Api(value = "抢拍订单", tags = "抢拍:抢拍订单", description = "抢拍订单")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class YxAuctionOrderController {

    private final YxAuctionOrderService  yxAuctionOrderService;
    private final YxAuctionRecordService yxAuctionRecordService;
    private final RedisTemplate redisTemplate;
//    private final YxAuctionOrderMapper userOrderMapper;
    private final UserMapper userMapper;
//    private final YxUserBillService yxUserBillService;
//    private final RedisTemplate redisTemplate;
    private final RedisUtils redisUtil;
//
//    public boolean lock(String key, int value, long releaseTime) {
//        key = "lock"+key;
//        // 尝试获取锁
//        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
//        // 判断结果
//        return boo != null && boo;
//    }
//    /**
//     *抢拍商品
//     * id为抢拍id
//     */
//    @GetMapping("/productOrder/seckillR")
//    @ApiOperation(value = "抢拍商品", notes = "抢拍商品")
//    public ApiResult seckillR(){
//
//
//            boolean lockPrice = lock("price"+898L,1,5);
//            System.out.println(1);
//        if(lockPrice){
//            Double f = Math.random()*10;
//            userOrderMapper.updateUserPrice(898L , new BigDecimal(f));
//            //记录
//            YxUser user = userMapper.selectById(898L);
//            //TB流水入库
//            YxUserBill userBill = YxUserBill.builder()
//                    .uid(user.getUid())
//                    .title("手续费支付")
//                    .category(BillDetailEnum.CATEGORY_1.getValue())
//                    .type(BillDetailEnum.TYPE_11.getValue())
//                    .number(new BigDecimal(f))
//                    .balance(user.getNowMoney())
//                    .mark("手续费支付")
//                    .status(BillEnum.STATUS_1.getValue())
//                    .payType(3)
//                    .orderNo("serviceMoney"+ RandonOrderNoUtil.getOrderIdByTime())
//                    .pm(BillEnum.PM_0.getValue())
//                    .build();
//            yxUserBillService.save(userBill);
//            System.out.println(2);
//            redisUtil.delete("lockprice"+898L);
//            System.out.println(3);
//            return ApiResult.ok("chenggong");
//        }else {
//            return ApiResult.ok("没锁了");
//        }
//
//    }


    /**
     *抢拍商品
     * id为抢拍id
     */
    @AuthCheck
    @AppNoRepeatSubmit
    @GetMapping("/productOrder/seckillRecord/{id}")
    @ApiOperation(value = "抢拍商品", notes = "抢拍商品")
    public ApiResult seckillRecord(@PathVariable String id) {
        YxUser yxUser=LocalUser.getUser();
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id)){
            throw new YshopException("参数错误");
        }
        return yxAuctionOrderService.seckillRecord(yxUser.getUid(),Long.valueOf(id));
    }


    /**
     *付款商品
     * id为订单id
     */
    @AuthCheck
    @PostMapping("/productOrder/payOrder")
    @ApiOperation(value = "付款商品", notes = "付款商品")
    public ApiResult<Object> payOrder(@Validated @RequestBody YxAuctionOrderParam yxAuctionOrderParam){
        YxUser yxUser=LocalUser.getUser();
       YxAuctionOrder yxAuctionOrder= yxAuctionOrderService.getById(Long.valueOf(yxAuctionOrderParam.getId()));
        if(null==yxAuctionOrder || 1==yxAuctionOrder.getIsDel()){
            throw new YshopException("订单不存在");
        }
        if(0 !=yxAuctionOrder.getStatus()){
            throw new YshopException("该笔订单不是待付款状态");
        }
        YxAuctionRecord yxAuctionRecord=yxAuctionRecordService.getById(yxAuctionOrder.getAuctionRecordId());
        if(4<yxAuctionOrderParam.getPayType()){
            throw new YshopException("支付方式错误");
        }
        if(null==yxAuctionRecord){
            throw new YshopException("该抢拍商品不存在");
        }
        //更新抢拍表
        yxAuctionRecord.setStatus(2);
        yxAuctionRecord.setConfirmVoucher(yxAuctionOrderParam.getConfirmVoucher());
        yxAuctionRecord.setPayType(yxAuctionOrderParam.getPayType());
        yxAuctionRecordService.updateById(yxAuctionRecord);
        //更新订单表
        yxAuctionOrder.setStatus(AuctionOrderEnum.TYPE_1.getValue());
        yxAuctionOrder.setPayTime(new Date());
        yxAuctionOrder.setPayType(yxAuctionOrderParam.getPayType());
        yxAuctionOrderService.updateById(yxAuctionOrder);


        //推送给卖家
        YxUser user = userMapper.selectById(yxAuctionRecord.getUserId());
        if (ObjectUtil.isNotEmpty(user)) PushtoSingle.sendToAlias("买家已付款","买家已付款，请及时确认",user.getClientId(),1,1L);

        Integer m = Integer.valueOf(String.valueOf(redisUtil.get("dict:mjzdsjfk")));
        String redisKey = String.valueOf(StrUtil.format("{}{}", ShopConstants.REDIS_AUCTION_ORDER_OUTTIME_UNCONFIRM, yxAuctionOrder.getId()));
        redisTemplate.opsForValue().set(redisKey, yxAuctionOrder.getOrderId() , m, TimeUnit.MINUTES);

        return ApiResult.ok("已上传凭证，等卖家确定");
    }


    /**
     *发起转拍
     * id为我的买单id
     */
    @AuthCheck
    @GetMapping("/productOrder/turnAuction")
    @NoRepeatSubmit
    @ApiOperation(value = "发起转拍", notes = "发起转拍")
    public ApiResult<Object> turnAuction(@RequestParam("id") String id, @RequestParam("payType") Integer payType,
                                         @RequestParam(value = "signatureImg",required = false)String signatureImg,
                                         @RequestParam(value = "payPassword",required = false)String payPassword,
                                         @RequestParam(value = "yjbl",required = false)String yjbl,

                                         HttpServletRequest request) throws ParseException {
        YxUser yxUser=LocalUser.getUser();
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id)){
            throw new YshopException("参数错误");
        }
       return yxAuctionOrderService.turnAuction(yxUser,id,payType,payPassword,signatureImg,yjbl,request);
    }



    @AuthCheck
    @GetMapping("/productOrder/getPopUpData")
    @NoRepeatSubmit
    @ApiOperation(value = "获取弹框中的数据", notes = "发起转拍")
    public ApiResult<Object> getPopUpData(@RequestParam("ids") String ids) throws ParseException {
        YxUser yxUser=LocalUser.getUser();
        if (StrUtil.isBlank(ids) || !NumberUtil.isNumber(ids)){
            throw new YshopException("参数错误");
        }
        return yxAuctionOrderService.getPopUpData(ids);

    }

    /**
     *一键转拍
     * id为我的买单id
     */
    @AuthCheck
    @GetMapping("/productOrder/oneKeyAuction")
    @NoRepeatSubmit
    @ApiOperation(value = "一键转拍", notes = "一键转拍")
    public ApiResult<Object> oneKeyAuction(@RequestParam("ids") String ids, @RequestParam("payType") Integer payType,
                                           @RequestParam(value = "signatureImg",required = false)String signatureImg,
                                           @RequestParam(value = "payPassword",required = false)String payPassword, HttpServletRequest request) throws ParseException {
        YxUser yxUser=LocalUser.getUser();
        if (StrUtil.isBlank(ids)){
            throw new YshopException("参数错误");
        }
        return yxAuctionOrderService.oneKeyAuction(yxUser,ids,payType,payPassword,signatureImg,request);
    }

    /**
     *获取总价
     * id为我的买单id
     */
    @AuthCheck
    @GetMapping("/productOrder/findTotalMoney")
    @ApiOperation(value = "获取总价", notes = "获取总价")
    public ApiResult<Object> findTotalMoney(@RequestParam("ids") String ids, HttpServletRequest request) throws ParseException {
        YxUser yxUser=LocalUser.getUser();
        if (StrUtil.isBlank(ids)){
            throw new YshopException("参数错误");
        }
        return yxAuctionOrderService.findTotalMoney(yxUser,ids,request);
    }



    /**
     *确认抢拍订单详情展示
     * id为我的买单id
     */
    @AuthCheck
    @GetMapping("/productOrder/confirmOrder/{id}")
    @ApiOperation(value = "确认抢拍订单详情展示", notes = "确认抢拍订单详情展示")
    public ApiResult<YxAuctionOrderConfirm> confirmOrder(@PathVariable String id){
        YxUser yxUser=LocalUser.getUser();
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id)){
            throw new YshopException("参数错误");
        }
       return yxAuctionOrderService.confirmOrder(yxUser.getUid(),Long.valueOf(id));
    }

    /**
     *确认订单
     * id为我的买单id
     */
    @AuthCheck
    @GetMapping("/productOrder/confirm")
    @ApiOperation(value = "确认订单", notes = "确认订单")
    public ApiResult<Object> confirm(@RequestParam("id") String id,@RequestParam("userAddressId")String userAddressId){
        YxUser yxUser=LocalUser.getUser();
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id) || StrUtil.isBlank(userAddressId) || !NumberUtil.isNumber(userAddressId)){
            throw new YshopException("参数错误");
        }
        return yxAuctionOrderService.confirm(yxUser.getUid(),Long.valueOf(id),Long.valueOf(userAddressId));
    }

    /**
     * 兑换积分
     */
    @AuthCheck
    @GetMapping("/productOrder/creditsExchange")
    @ApiOperation(value = "兑换积分", notes = "兑换积分")
    public ApiResult<Object> creditsExchange(@RequestParam("id") String id){
        YxUser yxUser=LocalUser.getUser();
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id)){
            throw new YshopException("参数错误");
        }
        return yxAuctionOrderService.creditsExchange(yxUser.getUid(),Long.valueOf(id));
    }

    /**
     *确认收货
     * id为我的买单id
     */
    @AuthCheck
    @GetMapping("/productOrder/finishOrder/{id}")
    @ApiOperation(value = "确认收货", notes = "确认收货")
    public ApiResult<Object> finishOrder(@PathVariable("id") String id){
        YxUser yxUser=LocalUser.getUser();
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id)){
            throw new YshopException("参数错误");
        }
       YxAuctionOrder yxAuctionOrder= yxAuctionOrderService.getById(Long.valueOf(id));
        if(null==yxAuctionOrder ||!yxUser.getUid().equals(yxAuctionOrder.getUserId())){
            throw new YshopException("订单不存在或者订单不属于该用户");
        }
        if(3 !=yxAuctionOrder.getStatus()){
            throw new YshopException("订单不属于待收货状态");
        }
        yxAuctionOrder.setStatus(AuctionOrderEnum.TYPE_4.getValue());
        yxAuctionOrderService.updateById(yxAuctionOrder);
        return ApiResult.ok("确认收货完成");
    }

    /**
     *待付款买单取消
     */
    @AuthCheck
    @GetMapping("/productOrder/cancelOrder/{id}")
    @ApiOperation(value = "待付款买单取消", notes = "待付款买单取消")
    public ApiResult<Object> cancelOrder(@PathVariable String id){
        YxUser yxUser=LocalUser.getUser();
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id)){
            throw new YshopException("参数错误");
        }
        YxAuctionOrder yxAuctionOrder=yxAuctionOrderService.getById(Long.valueOf(id));
        if(null==yxAuctionOrder || !yxUser.getUid() .equals(yxAuctionOrder.getUserId())){
            throw new YshopException("订单不存在或者订单不属于该用户");
        }
        if(0 !=yxAuctionOrder.getStatus()){
            throw new YshopException("订单不属于待付款状态，无法取消");
        }
        yxAuctionOrder.setStatus(AuctionOrderEnum.TYPE_5.getValue());
        yxAuctionOrderService.updateById(yxAuctionOrder);
        YxAuctionRecord yxAuctionRecord=yxAuctionRecordService.getById(yxAuctionOrder.getAuctionRecordId());
        if(null !=yxAuctionRecord){
            yxAuctionRecord.setIsBuy(0);
            yxAuctionOrderService.addRedis(yxAuctionRecord.getId());
            yxAuctionRecordService.updateById(yxAuctionRecord);
        }
        return ApiResult.ok("取消订单成功");
    }


    /**
     *我的买单列表
     */
    @AuthCheck
        @GetMapping("/productOrder/productOrderPage/{type}")
    @ApiOperation(value = "我的买单列表", notes = "我的买单列表")
    public ApiResult<Page<YxAuctionOrderList>> productOrderPage(@PathVariable String type,
                                                                @RequestParam(value = "page",defaultValue = "1") int page,
                                                                @RequestParam(value = "limit",defaultValue = "10") int limit){
        if (StrUtil.isBlank(type) || !NumberUtil.isNumber(type)){
            throw new YshopException("参数错误");
        }
        YxUser yxUser=LocalUser.getUser();
        return  yxAuctionOrderService.productOrderPage(yxUser.getUid(),Integer.valueOf(type),page,limit);
    }

    /**
     *我的买单历史记录
     */
    @AuthCheck
    @GetMapping("/productOrder/productHistoryOrderPage/{type}")
    @ApiOperation(value = "我的买单历史记录", notes = "我的买单历史记录")
    public ApiResult<Page<YxAuctionOrderList>> productHistoryOrderPage(@PathVariable String type,
                                                                @RequestParam(value = "page",defaultValue = "1") int page,
                                                                @RequestParam(value = "limit",defaultValue = "10") int limit){
        if (StrUtil.isBlank(type) || !NumberUtil.isNumber(type)){
            throw new YshopException("参数错误");
        }
        YxUser yxUser=LocalUser.getUser();
        return  yxAuctionOrderService.productHistoryOrderPage(yxUser.getUid(),Integer.valueOf(type),page,limit);
    }

    /**
     *我的买单详情
     */
    @AuthCheck
    @GetMapping("/productOrder/findAuctionOrderDetail/{id}")
    @ApiOperation(value = "我的买单详情", notes = "我的买单详情")
    public ApiResult<YxAuctionRecordDto> findAuctionOrderDetail(@PathVariable String id){
        if (StrUtil.isBlank(id) || !NumberUtil.isNumber(id)){
            throw new YshopException("参数错误");
        }
        YxUser yxUser=LocalUser.getUser();
        return  yxAuctionOrderService.findAuctionOrderDetail(yxUser.getUid(),Long.valueOf(id));
    }



}
